﻿// Licensed under GNU GPL V2.
// http://sps2010listmanager.codeplex.com/
// (c) 2010 by Daniel Bedarf

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Fluent;
using System.Diagnostics;
using Extensions;

namespace CodePlex.DBedarf.Sharepoint.ListManager
{

    public delegate void logJournalMessageDelegate(bool isError, string message, params object[] args);
    /// <summary>
    /// MainWindow of the application
    /// </summary>
    public partial class frmMain : RibbonWindow
    {

        const int UPDATECHECK_INTERVAL = 2;

        string _appDir;
        string _layouCfgFilename;
        string _settingFilename;

        /// <summary>
        /// flag that list data are currently readed and events should be ignored
        /// </summary>
        bool FlagReadingListDetails;

        /// <summary>
        /// Force a Update call for each element which is read from element collection (bad performance)
        /// </summary>
        bool FlagForceUpdate;
        /// <summary>
        /// the currently opend web
        /// </summary>
        Microsoft.SharePoint.SPWeb _currentWeb;

        /// <summary>
        /// the selected list or null
        /// </summary>
        Microsoft.SharePoint.SPList _currentSPList;
        FieldPropertyPage _fieldPropPage;

        #region UpdateHandler

        /// <summary>
        /// Gets or sets the last update check.
        /// </summary>
        /// <value>The last update check.</value>
        DateTime lastUpdateCheck
        {
            get
            {
                if (_Settings.ContainsKey("lastUpdateCheck") == false) lastUpdateCheck = DateTime.Now.AddDays(-UPDATECHECK_INTERVAL);
                try
                {
                    DateTime.Parse(_Settings["lastUpdateCheck"]);
                }
                catch (Exception)
                {
                    lastUpdateCheck = DateTime.Now.AddDays(-UPDATECHECK_INTERVAL);
                }
                return DateTime.Parse(_Settings["lastUpdateCheck"]);
            }
            set
            {
                if (_Settings.ContainsKey("lastUpdateCheck")) _Settings["lastUpdateCheck"] = value.ToString();
                else _Settings.Add("lastUpdateCheck", value.ToString());
            }
        }

        /// <summary>
        /// Handles the CheckUpdates event
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_CheckUpdates(object sender, RoutedEventArgs e)
        {
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(
                    new RoutedEventHandler(Useraction_CheckUpdates), new object[] { sender, e });
                return;
            }
            Cursor = Cursors.Wait;
            try
            {
                Update.IUpdater updater = new Update.Codeplex();
                Update.UpdateInfo udi;
                Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
                if (updater.IsUpdateAvailable(v, out udi))
                {
                    Cursor = Cursors.AppStarting;
                    if (WindowExtender.AskYesNo(
                        "Update available",
                        string.Format(
                            "The update \"{3}\" is available for this application.\n\n\tCurrent Version:\t{0}\n\tNew Version:\t{1}\n\n{2}\n\nDo you like to open the update page?",
                            v,
                            udi.Version,
                            udi.Message,
                            udi.Titel
                            )))
                    {
                        System.Diagnostics.Process.Start(udi.URL);
                    }
                }
                lastUpdateCheck = DateTime.Now;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            Cursor = Cursors.Arrow;
        }
        #endregion

        #region Settings

        /// <summary>
        /// Dynamic list of Settings
        /// </summary>
        Dictionary<string, string> _Settings;

        /// <summary>
        /// Saves the settings.
        /// </summary>
        private void saveSettings()
        {
            try
            {

                System.IO.StreamWriter sw = new System.IO.StreamWriter(_appDir + "\\settings.ini", false, System.Text.ASCIIEncoding.Default);
                foreach (KeyValuePair<string, string> kvp in _Settings)
                {
                    sw.WriteLine("{0}={1}", kvp.Key, kvp.Value.Replace("\n", "\\n").Replace("\r", "\\r"));
                }
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
                Exception e = new Exception("Error while saving the appsettings.\n\n" + ex.Message);
                HandleError(e);
            }
        }

        /// <summary>
        /// Reads the settings.
        /// </summary>
        private void readSettings()
        {
            _settingFilename = _appDir + "\\settings.ini";
            _Settings = new Dictionary<string, string>();
            try
            {

                if (System.IO.File.Exists(_settingFilename))
                {
                    foreach (string data in System.IO.File.ReadAllLines(_settingFilename, System.Text.ASCIIEncoding.Default))
                    {
                        _Settings.Add(data.Substring(0, data.IndexOf("=")), data.Substring(data.IndexOf("=") + 1).Replace("\\n", "\n").Replace("\\r", "\r"));
                    }

                }
            }
            catch (Exception ex)
            {
                //Just Ignore
                Trace.WriteLine(ex.StackTrace, "Error SPSListManager");
            }

        }
        #endregion

        #region AppStartEnd
        /// <summary>
        /// Initializes a new instance of the <see cref="frmMain"/> class.
        /// </summary>
        public frmMain()
        {
            _appDir = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Codeplex\\SharepointListManager";
            System.IO.Directory.CreateDirectory(_appDir);
            _layouCfgFilename = _appDir + "\\layout.cfg";
            FlagReadingListDetails = false;
            FlagForceUpdate = false;
            readSettings();
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Loaded event of the Window, make some settings and check for updates
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Version v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            this.Title = String.Format("Sharepoint 2010 - List Manager V{0}.{1} Rev({2})", v.Major, v.Minor, v.Revision);

            //Do a simple update check
            System.Threading.Thread t = new System.Threading.Thread(delegate()
            {
                //opt: set timespan to configfile
                if (DateTime.Now.DayOfYear - lastUpdateCheck.DayOfYear > UPDATECHECK_INTERVAL) Useraction_CheckUpdates(null, null);
                //new year
                if (DateTime.Now.DayOfYear - lastUpdateCheck.DayOfYear < 0) Useraction_CheckUpdates(null, null);
            });
            t.Start();

            //HACK: SettingManager bauen der die Contains-Prüfung automatisch macht
            if (_Settings.ContainsKey("notepad")) txtNotepad.Text = _Settings["notepad"];
            if (_Settings.ContainsKey("windowX1")) this.Left = 16 + double.Parse(_Settings["windowX1"]);
            if (_Settings.ContainsKey("windowY1")) this.Top = 30 + double.Parse(_Settings["windowY1"]);
            if (_Settings.ContainsKey("windowX2")) this.Width = double.Parse(_Settings["windowX2"]);
            if (_Settings.ContainsKey("windowY2")) this.Height = double.Parse(_Settings["windowY2"]);

            readRecentURLsFromSettings();
        }


        /// <summary>
        /// Handles the Loaded event of the DockingManager control and restore the saved layout
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void DockingManager_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (System.IO.File.Exists(_layouCfgFilename))
                {
                    _adDockManager.RestoreLayout(_layouCfgFilename);
                }
                CreateReadMeWindow();
                _ribbonManager.IsBackstageOpen = true;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        /// <summary>
        /// Creates the read me window. and show important informations
        /// </summary>
        private void CreateReadMeWindow()
        {
            try
            {
                InfoPage ip = new InfoPage();
                ip.Title = "ReadMe";
                ip.lblHeader.Content = this.Title;
                ip.lblContent.Text =
                    System.IO.File.ReadAllText(
                        System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\ReadMe.txt"
                        );
                //ip.IsCloseable = false;
                _DocumentPane.Items.Add(ip);
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        /// <summary>
        /// Creates a window with Text
        /// </summary>
        private void CreateInfoWindow(string Title, string Header, string Message)
        {
            try
            {
                InfoPage ip = new InfoPage();
                ip.Title = Title;
                ip.lblHeader.Content = Header;
                ip.lblContent.Text = Message;
                ip.IsCloseable = true;
                _DocumentPane.Items.Add(ip);
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        /// <summary>
        /// Creates a Window and Display a DataTables
        /// </summary>
        private void CreateDataWindow(string Title, string Header, System.Data.DataTable data)
        {
            try
            {
                //TODO R2 Data Page anlegen

                //Workaround
                string Message = "";
                foreach (System.Data.DataColumn col in data.Columns) Message += col.Caption + "\t";
                Message += "\n";
                foreach (System.Data.DataRow row in data.Rows)
                {
                    foreach (System.Data.DataColumn col in data.Columns) Message += (row[col] ?? "").ToString() + "\t";
                    Message += "\n";
                }
                //end workaround

                InfoPage ip = new InfoPage();
                ip.Title = Title;
                ip.lblHeader.Content = Header;
                ip.lblContent.Text = Message;
                ip.IsCloseable = true;
                _DocumentPane.Items.Add(ip);
                ip.SetAsActive();
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        /// <summary>
        /// Creates a window with Text
        /// </summary>
        private void CreateEditFieldWindow(List<Microsoft.SharePoint.SPField> fields)
        {
            try
            {
                if (_fieldPropPage == null)
                {
                    _fieldPropPage = new FieldPropertyPage(Useraction_ApplyColumnFilter, logJournal);
                    _fieldPropPage.Title = "Edit Column(s)";
                    _fieldPropPage.IsCloseable = true;
                }
                _fieldPropPage.Fields = fields;
                if (_DocumentPane.Items.Contains(_fieldPropPage) == false) _DocumentPane.Items.Add(_fieldPropPage);
                _fieldPropPage.SetAsActive();
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        ListEventReceiverPage _listEventHandlerPage;
        /// <summary>
        /// Creates a window to Manage EventReceivers on a List
        /// </summary>
        private void Create_HandleListEventReceiver_Page(List<Microsoft.SharePoint.SPList> lists)
        {
            try
            {
                if (_listEventHandlerPage == null)
                {
                    _listEventHandlerPage = new ListEventReceiverPage(logJournal);
                    _listEventHandlerPage.Title = "List - EventReceiver";
                    _listEventHandlerPage.IsCloseable = true;
                }
                _listEventHandlerPage.Lists = lists;
                if (_DocumentPane.Items.Contains(_listEventHandlerPage) == false) _DocumentPane.Items.Add(_listEventHandlerPage);
                _listEventHandlerPage.SetAsActive();
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        ListPropertyPage _listPropertyPage;
        private void Create_EditListPropertys_Page(Microsoft.SharePoint.SPList list)
        {
            try
            {
                if (_listEventHandlerPage == null)
                {
                    //TODO Callback lösen
                    _listPropertyPage = new ListPropertyPage(null, logJournal);
                    _listPropertyPage.Title = "List - Propertys";
                    _listPropertyPage.IsCloseable = true;
                }
                _listPropertyPage.Lists = list;
                if (_DocumentPane.Items.Contains(_listPropertyPage) == false) _DocumentPane.Items.Add(_listPropertyPage);
                _listPropertyPage.SetAsActive();
            }
            catch (Exception ex)
            {
                WindowExtender.ShowError(ex);
            }
        }

        /// <summary>
        /// Handles the Closing event of the Window, save settings and layout.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.ComponentModel.CancelEventArgs"/> instance containing the event data.</param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //HACK: SettingManager bauen der die Contains-Prüfung automatisch macht
            if (_Settings.ContainsKey("notepad")) _Settings["notepad"] = txtNotepad.Text;
            else _Settings.Add("notepad", txtNotepad.Text);

            //Hack: Settings.add mit prüfung ob existiert in eigne Funktion auslagern. Genau wie getvalue<T>. Default
            if (_Settings.ContainsKey("windowX1")) _Settings["windowX1"] = this.Left.ToString(); else _Settings.Add("windowX1", this.Left.ToString());
            if (_Settings.ContainsKey("windowY1")) _Settings["windowY1"] = this.Top.ToString(); else _Settings.Add("windowY1", this.Top.ToString());
            if (_Settings.ContainsKey("windowX2")) _Settings["windowX2"] = this.Width.ToString(); else _Settings.Add("windowX2", this.Width.ToString());
            if (_Settings.ContainsKey("windowY2")) _Settings["windowY2"] = this.Height.ToString(); else _Settings.Add("windowY2", this.Height.ToString());

            saveRecentURLsToSettings();
            Action_SaveDockingLayout();
            saveSettings();
        }


        /// <summary>
        /// Handles the CloseApp event and forces the app to quit
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_CloseApp(object sender, RoutedEventArgs e)
        {
            //TODO R3: Check for unsaved changes
            this.Close();
        }

        /// <summary>
        /// save the layout of docking windows
        /// </summary>
        private void Action_SaveDockingLayout()
        {
            try
            {
                if (_adDockManager != null) _adDockManager.SaveLayout(_layouCfgFilename);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region RecentURLs
        /// <summary>
        /// Creates the recent files menue.
        /// </summary>
        private void readRecentURLsFromSettings()
        {
            tabCtrlRecentFiles.Items.Clear();
            for (int i = 0; i < 10; i++)
            {
                string key = "url" + i.ToString("00");
                if (_Settings.ContainsKey(key))
                {
                    string url = _Settings[key];
                    string title = "";
                    if (_Settings.ContainsKey(key + "Text")) title = _Settings[key + "Text"];

                    addRecentURL(url, title);
                }
            }
        }

        /// <summary>
        /// Saves the recent URls to settings collection
        /// </summary>
        private void saveRecentURLsToSettings()
        {
            //delete old data
            for (int i = 0; i < 10; i++)
            {
                string key = "url" + i.ToString("00");
                _Settings.Remove(key);
                _Settings.Remove(key + "Text");
            }

            //save new data
            Dictionary<string, string> recentURLs = getRecentURLs();
            string[] keys = recentURLs.Keys.ToArray();
            for (int i = 0; i < 10 && i < recentURLs.Count(); i++)
            {

                string key = "url" + i.ToString("00");
                _Settings.Add(key, keys[i]);
                _Settings.Add(key + "Text", recentURLs[keys[i]]);
            }
        }

        /// <summary>
        /// Adds the recent URL to all menues at last position
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="Title">Name of the website</param>
        private void addRecentURL(string url, string Title)
        {
            addRecentURL(url, Title, false);
        }

        /// <summary>
        /// Adds the recent URL to all menues
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="Title">Name of the website</param>
        /// <param name="isFirst">true: move to first position</param>
        private void addRecentURL(string url, string Title, bool isFirst)
        {
            //ignore localhost
            if (url.Equals(Properties.Settings.Default.Localhost, StringComparison.CurrentCultureIgnoreCase)) return;

            //find url and move to top
            foreach (string u in getRecentURLs().Keys)
            {
                if (u.Equals(url, StringComparison.CurrentCultureIgnoreCase))
                {
                    if (isFirst)
                    {
                        //TODO R3: sort item to first position
                    }
                    return;
                }
            }

            //Hack: optimieren über controltemplate
            TabItem ti = new TabItem();
            ti.Tag = url; //important, this will be checkd to connect !!!

            //create controlstack for header
            StackPanel sp = new StackPanel();
            BitmapImage bi = new BitmapImage();
            bi.CacheOption = BitmapCacheOption.OnLoad;
            //TODO R2 - change to control
            bi.UriSource = new Uri("pack://application:,,,/Images/recenturl.png");
            Image i = new Image { Source = bi };
            //i.Source = bi;
            i.Margin = new Thickness(0, 0, 4, 0);
            sp.Children.Add(i);

            TextBlock tb = new TextBlock();
            tb.Text = Title;
            if (string.IsNullOrEmpty(Title))
            {
                tb.Text = url;
                sp.Children.Add(tb);
            }
            else
            {
                sp.Children.Add(tb);
                Label r = new Label();
                r.Content = url;
                r.Foreground = Brushes.DimGray;
                sp.Children.Add(r);
                ti.Header = sp;
            }
            ti.Header = sp;
            //db-cs  ti.Header = url;

            //TODO R2 Hier am besten nur das Bild anzeigen (dateinamen url00.png im appdir)

            //WebBrowser wb = new WebBrowser();
            //wb.Navigate(new Uri("http://localhost"));//"<b>WEBSEITE</b>");
            //wb.IsEnabled = false;
            //wb.drawtobitmap
            //ti.Content = wb;
            ti.Margin = new Thickness(5);
            //TODO R2 RecentURL - Contenet ablegen
            TextBlock tbContent = new TextBlock();
            tbContent.Text = "please doubleclick to connect";
            tbContent.Margin = new Thickness(20);
            ti.Content = tbContent;
            ti.MouseDoubleClick += new MouseButtonEventHandler(Useraction_ConnectToRecentURL);
            if (isFirst)
                tabCtrlRecentFiles.Items.Insert(0, ti);
            else
                tabCtrlRecentFiles.Items.Add(ti);
        }

        void Useraction_ConnectToRecentURL(object sender, MouseButtonEventArgs e)
        {
            Useraction_ConnectToRecentURL(sender, (SelectionChangedEventArgs)null);
        }


        /// <summary>
        /// Gets the recent URls from menues.
        /// </summary>
        /// <returns>a list with url - title</returns>
        private Dictionary<string, string> getRecentURLs()
        {
            Dictionary<string, string> urls = new Dictionary<string, string>();
            foreach (TabItem ti in tabCtrlRecentFiles.Items)
            {
                if (ti.Tag != null)
                {
                    //todo: recent url  add title
                    urls.Add(ti.Tag.ToString(), "");
                }
            }
            return urls;
        }


        /// <summary>
        /// Gets the selected recent URL.
        /// </summary>
        /// <returns></returns>
        private string getSelectedRecentURL()
        {
            TabItem ti = tabCtrlRecentFiles.SelectedItem as TabItem;
            if (ti != null)
            {
                return ti.Tag.ToString();
            }
            return "";
        }
        #endregion

        #region App-Helpers
        /// <summary>
        /// Show a Message and log the error.
        /// </summary>
        /// <param name="ex">The ex.</param>
        private void HandleError(Exception ex)
        {
            WindowExtender.ShowError(ex);
            logJournal(true, "Error: {0}", ex.Message);
        }

        /// <summary>
        /// Logs a message to the  journal.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="args">The args.</param>
        private void logJournal(string message, params object[] args)
        {
            logJournal(false, message, args);
        }

        /// <summary>
        ///  Logs a message to the  journal.
        /// </summary>
        /// <param name="isError">if set to <c>true</c> [is error].</param>
        /// <param name="message">The message.</param>
        /// <param name="args">The args.</param>
        private void logJournal(bool isError, string message, params object[] args)
        {
            try
            {
                ListViewItem lvi = new ListViewItem();
                if (isError) lvi.Background = Brushes.Yellow;
                lvi.Content = new KeyValuePair<DateTime, string>(DateTime.Now, string.Format(message, args));
                lvwJournal.Items.Add(lvi);
            }
            catch (Exception)
            {
                //ignore
            }
        }
        #endregion

        #region UI-Helper

        private List<Microsoft.SharePoint.SPField> getSelectedFields()
        {
            List<Microsoft.SharePoint.SPField> fields = new List<Microsoft.SharePoint.SPField>();
            foreach (System.Windows.Controls.ListViewItem li in lvwFields.SelectedItems)
            {
                Microsoft.SharePoint.SPField f = li.Content as Microsoft.SharePoint.SPField;
                if (f != null) fields.Add(f);
            }
            return fields;
        }

        /// <summary>
        /// Gets the selected lists only from list table and from server - explorer
        /// </summary>
        /// <returns></returns>
        private List<Microsoft.SharePoint.SPList> getSelectedLists()
        {
            List<Microsoft.SharePoint.SPList> lists = new List<Microsoft.SharePoint.SPList>();
            //table
            foreach (System.Windows.Controls.ListViewItem li in lvwLists.SelectedItems)
            {
                Microsoft.SharePoint.SPList f = li.Content as Microsoft.SharePoint.SPList;
                if (f != null) lists.Add(f);
            }
            //server explorer
            if (lists.Contains(_currentSPList) == false) lists.Add(_currentSPList);
            return lists;
        }
        #endregion

        #region Connect to SPS
        private void Useraction_ConnectToRecentURL(object sender, SelectionChangedEventArgs e)
        {
            string url = getSelectedRecentURL();
            if (string.IsNullOrEmpty(url) == false)
            {
                Action_ConnectServer(url);
                _ribbonManager.IsBackstageOpen = false;
            }
        }

        private void Useraction_ConnectToServerURL(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txtBackStageURL.Text) == false)
                    Action_ConnectServer(txtBackStageURL.Text);
                else
                    Action_ConnectServer(txtBackStageURL.Text);

                _ribbonManager.IsBackstageOpen = false;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        private void Useraction_ConnectToLocalhost(object sender, RoutedEventArgs e)
        {
            try
            {
                Action_ConnectServer(Properties.Settings.Default.Localhost);
                _ribbonManager.IsBackstageOpen = false;
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Action_ConnectServer(string URL)
        {
            Cursor c = Cursor;
            this.Cursor = Cursors.Wait;
            try
            {
                if (_currentWeb != null) if (_currentWeb.Url.Equals(URL, StringComparison.CurrentCultureIgnoreCase)) return;

                txtBackStageURL.Text = URL;
                Action_ResetRibbons();

                Action_ShowSubWebs(null);
                Action_ShowLists(null);
                Action_ShowFields(null);

                using (Microsoft.SharePoint.SPSite SPSite = new Microsoft.SharePoint.SPSite(URL))
                {
                    Microsoft.SharePoint.SPWeb SPWeb = SPSite.OpenWeb();
                    _currentWeb = SPWeb;
                    logJournal("Connected to {0}", _currentWeb.Url);
                    addRecentURL(_currentWeb.Url, _currentWeb.Title, true);
                    Action_ResetRibbons();
                    Action_ShowSubWebs(_currentWeb);
                    Action_ShowLists(_currentWeb);
                }

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                this.Cursor = c;
            }
        }
        #endregion

        #region Actions

        /// <summary>
        /// the show sub webs in tree or lists
        /// </summary>
        /// <param name="SPWeb">The SP web.</param>
        private void Action_ShowSubWebs(Microsoft.SharePoint.SPWeb SPWeb)
        {
            tvwNodeWeb.Items.Clear();
            if (SPWeb == null) return;
            if (FlagForceUpdate) SPWeb.Update();

            foreach (Microsoft.SharePoint.SPWeb web in SPWeb.Webs)
            {
                SPSTreeNode subnode = new SPSTreeNode(SPSTreeNode.eTreeNodeType.SPWeb);
                subnode.Text = web.Title;
                subnode.SPWeb = web;
                subnode.MouseDoubleClick += new MouseButtonEventHandler(Event_ServerExplorerWebDblClick);
                tvwNodeWeb.Items.Add(subnode);
            }
        }

        /// <summary>
        /// Handles the MouseDoubleClick event of a SPWeb node control in ServerExplorer
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        void Event_ServerExplorerWebDblClick(object sender, MouseButtonEventArgs e)
        {
            SPSTreeNode node = tvwServerExplorer.SelectedItem as SPSTreeNode;
            if (node == null) return;
            if (node.NodeType == SPSTreeNode.eTreeNodeType.SPWeb)
            {
                Action_ConnectServer(node.SPWeb.Url);
            }
        }


        /// <summary>
        /// Action show all lists on the current web
        /// </summary>
        /// <param name="SPWeb">The SP web.</param>
        private void Action_ShowLists(Microsoft.SharePoint.SPWeb SPWeb)
        {
            try
            {
                //save old id to reselect
                Guid oldID = Guid.Empty;
                if (_currentSPList != null) oldID = _currentSPList.ID;

                tvwNodeLists.Items.Clear();
                tvwNodeDocLibs.Items.Clear();
                lvwLists.Items.Clear();
                ribbonGroupList.Visibility = Visibility.Hidden;
                ribbonGroupTools.Visibility = Visibility.Hidden;

                Action_ShowFields(null);
                if (SPWeb == null) return;

                //get new lists e.g.
                //opt: find a readonly update method
                if (FlagForceUpdate) SPWeb.Update();

                ListViewItem liFound = null;

                foreach (Microsoft.SharePoint.SPList list in SPWeb.Lists)
                {
                    //opt: find a readonly update method
                    if (FlagForceUpdate) list.Update();//get new data
                    bool isDocLib = list is Microsoft.SharePoint.SPDocumentLibrary;
                    if (
                        ((filterListUserLists.IsChecked && list.Hidden == false) || (list.Hidden == true && filterListHidden.IsChecked))
                        &&
                        (isDocLib == false || (isDocLib && filterListDokLib.IsChecked))
                        &&
                        ((filterListUserLists.IsChecked && list.AllowDeletion == true) || (list.AllowDeletion == false && filterListCatalogs.IsChecked))
                       )
                    {
                        SPSTreeNode listnode = new SPSTreeNode(SPSTreeNode.eTreeNodeType.SPList);
                        listnode.Text = list.Title;
                        listnode.SPList = list;

                        ListViewItem li = new ListViewItem();
                        li.Content = list;
                        lvwLists.Items.Add(li);
                        if (list.ID == oldID) liFound = li;

                        if (isDocLib)
                        {
                            listnode.NodeType = SPSTreeNode.eTreeNodeType.SPDocLib;
                            tvwNodeDocLibs.Items.Add(listnode);
                        }
                        else
                        {
                            if (list.Hidden) listnode.setListImageHidden();
                            else if (!list.AllowDeletion) listnode.setListImageRO();
                            tvwNodeLists.Items.Add(listnode);
                        }

                    }//end if filter
                }//end for each list
                if (liFound != null) lvwLists.SelectedItem = liFound;

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
            }

        }


        /// <summary>
        /// show fields to the selected list or clear the field - list
        /// </summary>
        /// <param name="SPList">The SP list.</param>
        private void Action_ShowFields(Microsoft.SharePoint.SPList SPList)
        {
            lvwFields.Items.Clear();
            ribbonTabEditField.IsSelected = false;
            ribbonGroupFields.Visibility = Visibility.Hidden;

            if (SPList == null) return;

            //get new fields e.g.
            //opt: find a readonly update method
            if (FlagForceUpdate) SPList.Update();

            foreach (Microsoft.SharePoint.SPField field in SPList.Fields)
            {
                //get new fieldsettings from web
                //opt: find a readonly update method
                if (FlagForceUpdate) field.Update();

                bool bShow = false;

                //do some checks like if(field has property then check filter for prop else ignore prop)
                bShow = filterFieldStd.IsChecked;
                bShow = field.Required ? (filterFieldRequired.IsChecked) : bShow;
                bShow = field.CanBeDeleted == false ? (filterFieldDeletable.IsChecked) : bShow;
                bShow = field.ReadOnlyField ? (filterFieldReadOnly.IsChecked) : bShow;
                bShow = field.Hidden ? (filterFieldHidden.IsChecked) : bShow;
                bShow = field.TypeAsString.Equals("computed", StringComparison.CurrentCultureIgnoreCase) ? filterFieldComputed.IsChecked : bShow;

                if (bShow)
                {
                    //grundsätzlich Anzeige erlaubt
                    ListViewItem li = new ListViewItem();
                    li.Content = field;
                    lvwFields.Items.Add(li);
                }

            }
        }

        #endregion

        #region Useractions

        /// <summary>
        /// reread columns of currentlist
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ApplyColumnFilter(object sender, RoutedEventArgs e)
        {
            try
            {
                Action_ShowFields(_currentSPList);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        //private void Useraction_ReloadServerExplorer(object sender, RoutedEventArgs e)
        //{
        //    Action_ShowSubWebs(_currentWeb);
        //    Action_ShowLists(_currentWeb);
        //    Action_ShowFields(null);
        //}

        private void Useraction_ApplyListFilter(object sender, RoutedEventArgs e)
        {
            try
            {
                Action_ShowLists(_currentWeb);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Event_ServerExplorer_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            try
            {
                ribbonGroupList.Visibility = Visibility.Hidden;
                ribbonGroupFields.Visibility = Visibility.Hidden;
                ribbonGroupTools.Visibility = Visibility.Hidden;
                ribbonTabEditField.IsSelected = false;
                ribbonTabEditList.IsSelected = false;
                ribbonTabStart.IsSelected = true;

                SPSTreeNode node = tvwServerExplorer.SelectedItem as SPSTreeNode;
                if (node != null)
                {
                    switch (node.NodeType)
                    {
                        case SPSTreeNode.eTreeNodeType.SPWeb:
                            Action_SubWebSelected(node.SPWeb);
                            break;
                        case SPSTreeNode.eTreeNodeType.SPList:
                            Action_ShowListDetails(node.SPList);
                            break;
                        case SPSTreeNode.eTreeNodeType.SPDocLib:
                            Action_ShowListDetails(node.SPList);
                            break;
                        default:
                            Action_ShowListDetails(null);
                            WindowExtender.ShowInfo("currently not supported");
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Action_ShowListDetails(Microsoft.SharePoint.SPList SPList)
        {
            //no circle action if we select in tree and lists
            if (FlagReadingListDetails) return;

            FlagReadingListDetails = true;
            try
            {

                //TODO R2 refresh Detailspage
                //TODO R2 alle ELemente im Explorer und lvwLists durchgehen und identische zu SPList markieren
                //Wichtig: selectuion changed durch Flag verhindern
                _currentSPList = SPList;
                if (SPList != null)
                {
                    ribbonGroupList.Visibility = Visibility.Visible;
                    ribbonTabEditField.IsSelected = false;
                    ribbonTabEditList.IsSelected = true;

                    //TODO R3 ribbonGroupTools.Visibility = Visibility.Visible;
                    cmdOpenItemInBrowser.IsEnabled = true;
                    cmdOpenItemInSPD.IsEnabled = true;
                    chkCurrentListHidden.IsChecked = SPList.Hidden;
                    chkCurrentListNotDeleteable.IsChecked = !SPList.AllowDeletion;

                    Action_ShowFields(SPList);

                    ribbonGroupList.Visibility = Visibility.Visible;
                    ribbonTabEditField.IsSelected = false;
                    ribbonTabEditList.IsSelected = true;

                    if (_listEventHandlerPage != null) _listEventHandlerPage.Lists = getSelectedLists();
                    if (_listPropertyPage != null) _listPropertyPage.Lists = _currentSPList;
                }
                else
                {
                    Action_ResetRibbons();

                    cmdOpenItemInBrowser.IsEnabled = false;
                    cmdOpenItemInSPD.IsEnabled = false;
                    Action_ShowFields(null);
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                FlagReadingListDetails = false;
            }

        }

        /// <summary>
        /// reset ribbons and show the "start" items
        /// </summary>
        private void Action_ResetRibbons()
        {
            ribbonGroupFields.Visibility = Visibility.Hidden;
            ribbonGroupList.Visibility = Visibility.Hidden;
            ribbonGroupTools.Visibility = Visibility.Hidden;
            ribbonTabEditField.IsSelected = false;
            ribbonTabEditList.IsSelected = false;
            ribbonTabStart.IsSelected = true;
        }


        /// <summary>
        /// Shows Details to the selected SubWeb
        /// </summary>
        /// <param name="SPWeb">The SP web.</param>
        private void Action_SubWebSelected(Microsoft.SharePoint.SPWeb SPWeb)
        {
            cmdOpenItemInBrowser.IsEnabled = false;
            cmdOpenItemInSPD.IsEnabled = false;
            if (SPWeb != null)
            {
                //HACK: refresh Detailpage wenn wieder aktiv
                cmdOpenItemInBrowser.IsEnabled = true;
                cmdOpenItemInSPD.IsEnabled = true;
            }
        }

        /// <summary>
        /// SHow a URL in a Browser.
        /// Encapulated for later Use e.g. an internal Browser Window
        /// </summary>
        /// <param name="url"></param>
        private void Action_OpenBrowser(string url)
        {
            if (string.IsNullOrEmpty(url)) throw new Exception("No URL specified");
            try
            {
                System.Diagnostics.Process.Start(url);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Gets the current URL of selected List or Web to show in Browser or open Editor
        /// </summary>
        /// <returns>URL to a List or Web</returns>
        private string getCurrentItemURL()
        {
            string url = _currentWeb.Url;
            if (_currentSPList != null)
            {
                //für spätere Unterscheidung
                if (_currentSPList is Microsoft.SharePoint.SPDocumentLibrary)
                {
                    url = _currentWeb.Site.MakeFullUrl(_currentSPList.DefaultViewUrl);
                }
                else
                {
                    url = _currentWeb.Site.MakeFullUrl(_currentSPList.DefaultViewUrl);
                }
            }
            return url;
        }

        private void Useraction_ShowListDetails(object sender, SelectionChangedEventArgs e)
        {
            if (lvwLists.SelectedItem == null) return;
            //HACK: ExplorerSelection verbergen  if(tvwServerExplorer.SelectedItem != null) tvwServerExplorer.SelectedItem.;
            Microsoft.SharePoint.SPList List = ((ListViewItem)lvwLists.SelectedItem).Content as Microsoft.SharePoint.SPList;
            if (List != null)
                Action_ShowListDetails(List);
        }

        private void Useraction_ShowFieldDetails(object sender, SelectionChangedEventArgs e)
        {
            if (lvwFields.SelectedItems.Count >= 0)
            {
                ribbonGroupFields.Visibility = Visibility.Visible;
                ribbonTabEditField.IsSelected = true;
                if (_fieldPropPage != null)
                {
                    _fieldPropPage.Fields = getSelectedFields();
                }
            }
            else
            {
                ribbonGroupFields.Visibility = Visibility.Hidden;
                if (_fieldPropPage != null) _fieldPropPage.Close();
            }
        }

        /// <summary>
        /// Handles the ToggleListVisibility event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Useraction_ToggleListVisibility(object sender, EventArgs e)
        {
            try
            {
                //check that we don't get a roundtrip
                if (FlagReadingListDetails) return;

                if (_currentSPList == null) return;
                _currentSPList.Hidden = chkCurrentListHidden.IsChecked;
                _currentSPList.Update();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the ToggleListDeletability event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Useraction_ToggleListDeletability(object sender, EventArgs e)
        {
            try
            {
                //check that we don't get a roundtrip
                if (FlagReadingListDetails) return;

                if (_currentSPList == null) return;
                _currentSPList.AllowDeletion = !chkCurrentListNotDeleteable.IsChecked;
                _currentSPList.Update();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }


        private void Useraction_ResetRoleInheritancesForWeb(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (Microsoft.SharePoint.SPSite sps = new Microsoft.SharePoint.SPSite(_currentWeb.Site.ID))
                    {
                        Microsoft.SharePoint.SPWeb w = sps.OpenWeb(_currentWeb.ID);
                        if (WindowExtender.AskYesNo("Reset RoleInheritance", "Are you sure to reset the web-security for\n\"{0}\" ({1})\nand inherit rights from parent web?", w.Title, w.Url) == true)
                        {
                            w.ResetRoleInheritance();
                        }
                    }
                });
            }
            catch (Exception ex)
            {

                System.Diagnostics.Debug.WriteLine(ex.ToString());
                WindowExtender.ShowError(ex);
            }
        }

        #endregion

        #region ShowActions

        private void Useraction_ShowListPane(object sender, RoutedEventArgs e)
        {
            _adDockManager.Show(_ListsPane);
        }

        private void Useraction_ShowExplorerPane(object sender, RoutedEventArgs e)
        {
            _adDockManager.Show(_ServerExplorerPane);
        }

        private void Useraction_ShowPropertyPane(object sender, RoutedEventArgs e)
        {
            throw new NotSupportedException();
            //_adDockManager.Show(_PropertiePane);
        }

        private void Useraction_ShowFieldPane(object sender, RoutedEventArgs e)
        {
            _adDockManager.Show(_FieldsPane);
        }

        private void Useraction_ShowJournalPane(object sender, RoutedEventArgs e)
        {
            _adDockManager.Show(_JournalPane);
        }

        private void Useraction_ShowNotesPane(object sender, RoutedEventArgs e)
        {
            _adDockManager.Show(_NotesPane);
        }


        #endregion

        #region Tools
        /// <summary>
        /// opens browser
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_OpenItemInBrowser(object sender, RoutedEventArgs e)
        {
            try
            {
                string url = getCurrentItemURL();
                Action_OpenBrowser(url);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }


        /// <summary>
        /// opens sharepointdesigner
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_OpenItemInSPD(object sender, RoutedEventArgs e)
        {
            try
            {

                if (_currentSPList != null)
                {
                    System.Diagnostics.Process.Start(
                        System.Environment.ExpandEnvironmentVariables(Properties.Settings.Default.SPDPath),
                        string.Format("/dde \"{0}/?CMD=EditList&ListId={1}\"", _currentWeb.Site.MakeFullUrl(""), _currentSPList.ID.ToString("B")));
                }
                else
                {
                    System.Diagnostics.Process.Start(
                        System.Environment.ExpandEnvironmentVariables(Properties.Settings.Default.SPDPath),
                        string.Format("/dde \"{0}\"", _currentWeb.Site.MakeFullUrl("")));
                }//endif current list !0 null else
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }


        /// <summary>
        /// runs iisreset
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Useraction_IISReset(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("iisreset.exe");
                logJournal("iisreset");
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_OpenPowershell(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start("PowerShell.exe", System.Environment.ExpandEnvironmentVariables(Properties.Settings.Default.PowerShellArgs));
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_OpenInstallDir(object sender, RoutedEventArgs e)
        {
            try
            {
                //OPT: Remote Server beachten und dann UNC \\server\c$ aufmachen
                System.Diagnostics.Process.Start("explorer.exe", System.Environment.ExpandEnvironmentVariables(Properties.Settings.Default.SPSInstallDir));
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_OpenWWWDir(object sender, RoutedEventArgs e)
        {
            try
            {
                //OPT: Remote Server beachten und dann UNC \\server\c$ aufmachen
                System.Diagnostics.Process.Start("explorer.exe", System.Environment.ExpandEnvironmentVariables(Properties.Settings.Default.Inetpup));
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the ShowManageRights event 
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ShowManageRights(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentSPList != null)
                {
                    string url = string.Format("{0}/_layouts/user.aspx?obj={1},list&list={1}", _currentWeb.Url, _currentSPList.ID.ToString("B"));
                    Action_OpenBrowser(url);
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        private void Useraction_ShowListSettingsWeb(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentSPList != null)
                {
                    string url = string.Format("{0}/_layouts/listedit.aspx?List={1}", _currentWeb.Url, _currentSPList.ID.ToString("B"));
                    Action_OpenBrowser(url);
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_ShowListAddView(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentSPList != null)
                {
                    string url = string.Format("{0}/_layouts/ViewType.aspx?List={1}", _currentWeb.Url, _currentSPList.ID.ToString("B"));
                    Action_OpenBrowser(url);
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the DeleteListContent event
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_DeleteListContent(object sender, RoutedEventArgs e)
        {
            try
            {
                if (WindowExtender.AskYesNo("delete content...", "Are you sure to delete all content in the list \"{0}\" ?", _currentSPList.Title))
                {
                    for (int i = 0; i < _currentSPList.ItemCount; i++)
                    {
                        _currentSPList.Items.Delete(0);
                    }
                    _currentSPList.Update();
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the DeleteList event
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_DeleteList(object sender, RoutedEventArgs e)
        {
            try
            {
                if (WindowExtender.AskYesNo("delete list...", "Are you sure you want delete the list \"{0}\" with all settings and data?", _currentSPList.Title))
                {
                    string title = _currentSPList.Title;
                    _currentSPList.Delete();
                    Action_ShowLists(_currentWeb);
                    logJournal("List \"{0}\" deleted on web {1}", title, _currentWeb.Url);
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_ShowCurrentListData(object sender, RoutedEventArgs e)
        {
            try
            {
                Microsoft.SharePoint.SPListItemCollectionPosition po = new Microsoft.SharePoint.SPListItemCollectionPosition("");
                CreateDataWindow(
                    "Data - " + _currentSPList.Title,
                    _currentSPList.Title,
                    _currentSPList.GetDataTable(new Microsoft.SharePoint.SPQuery(_currentSPList.DefaultView), Microsoft.SharePoint.SPListGetDataTableOptions.None, out po));
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_EditListPropertys(object sender, RoutedEventArgs e)
        {
            try
            {
                Create_EditListPropertys_Page(_currentSPList);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_AddEventhandlerToList(object sender, RoutedEventArgs e)
        {
            try
            {
                Create_HandleListEventReceiver_Page(getSelectedLists());
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_ShowListEventhandler(object sender, RoutedEventArgs e)
        {
            try
            {
                Create_HandleListEventReceiver_Page(getSelectedLists());
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_ShowEditFieldPage(object sender, RoutedEventArgs e)
        {
            try
            {
                CreateEditFieldWindow(getSelectedFields());
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_ShowAddField(object sender, RoutedEventArgs e)
        {

            try
            {
                if (_currentSPList != null)
                {
                    string url = string.Format("{0}/_layouts/fldNew.aspx?List={1}", _currentWeb.Url, _currentSPList.ID.ToString("B"));
                    Action_OpenBrowser(url);
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        private void Useraction_DeleteField(object sender, RoutedEventArgs e)
        {
            try
            {
                foreach (Microsoft.SharePoint.SPField field in getSelectedFields())
                {
                    if (WindowExtender.AskYesNo("delete columns...", "Delete column \"{0}\" ?", field.Title))
                    {
                        string title = field.Title;

                        field.Delete();
                        logJournal("Column \"{0}\" deleted in \"{1}\" ({2})", title, _currentSPList.Title, _currentWeb.Url);
                    }
                }
                _currentSPList.Update();
                Action_ShowFields(_currentSPList);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        /// <summary>
        /// Handles the ReloadColumns event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ReloadColumns(object sender, RoutedEventArgs e)
        {
            try
            {
                FlagForceUpdate = true;
                Action_ShowFields(_currentSPList);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                FlagForceUpdate = false;
            }
        }

        /// <summary>
        /// Handles the ReloadLists event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ReloadLists(object sender, RoutedEventArgs e)
        {
            try
            {
                FlagForceUpdate = true;
                Action_ShowLists(_currentWeb);
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
            finally
            {
                FlagForceUpdate = false;
            }
        }

        /// <summary>
        /// Handles the ShowReadMe event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ShowReadMe(object sender, RoutedEventArgs e)
        {
            CreateReadMeWindow();
        }

        #region OpenContact

        /// <summary>
        /// Handles the ContactCodeplex event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ContactCodeplex(object sender, RoutedEventArgs e)
        {
            Action_OpenBrowser("http://sps2010listmanager.codeplex.com/Thread/List.aspx");
        }

        /// <summary>
        /// Handles the ContactXing event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ContactXing(object sender, RoutedEventArgs e)
        {
            Action_OpenBrowser("http://www.xing.com/profile/Daniel_Bedarf");
        }

        /// <summary>
        /// Handles the ContactTwitter event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ContactTwitter(object sender, RoutedEventArgs e)
        {
            Action_OpenBrowser("http://www.twitter.com/blndev");
        }

        /// <summary>
        /// Handles the ContactTwitter event of the Useraction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Useraction_ContactYouTube(object sender, RoutedEventArgs e)
        {
            Action_OpenBrowser("http://www.youtube.com/user/HowTo453");
        }
        #endregion

        #endregion

    }
}
